<?php

namespace App\Http\Controllers;

use App\Business\BLL\QqMap;
use App\Http\Controllers\Controller;
use App\Models\Sect;
use App\Models\SectChangeLog;
use App\Models\SectMember;
use App\Models\WechatUser;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class SectController extends Controller
{
    function list() {
        $pn = request()->input('pn', config('api.page_num'));
        $city = request()->input('city', '');
        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city .= '%';

        $status = request()->input('status', 20);

        $column = ['id', 'name', 'point', 'member_count', 'level_limit', 'score_limit'];

        $list = Sect::where([['city', 'like', $city], ['status', $status]])
            ->withCount('member')
            ->orderBy('point', 'desc')
            ->paginate($pn);
        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }

    function new (Request $request) {
        $userId = request()->input('user_id');
        $userInfo = WechatUser::find($userId);

        if (empty($userInfo->city)) {
            return response()->json([
                'recode' => 0,
                'msg' => '请先定位城市',
            ]);
        }

        $file = $request->file("file");
        $headAvatar = 'default/default_avatar.jpeg';
        if ($file) {
            $disk = \Storage::disk('qiniu');
            $headAvatar = $disk->put('sect/', $file);
        }

        $name = request()->input('name');
        $shortName = request()->input('short_name');

        $coach = request()->input('coach');
        $tele = request()->input('tele');
        $charge = request()->input('charge');

        if (empty($headAvatar)) {
            $headAvatar = 'default/default_avatar.jpeg';
        }

        //检查队名是否存在
        $sectCheck = Sect::where([['name', $name], ['status', '!=', 90]])->first();
        if ($sectCheck) {
            return response()->json([
                'recode' => 0,
                'msg' => '名称已经存在',
            ]);
        }

        $imgUrls = request()->input('imgurls', '');
        $del = request()->input('del');
        //删除旧资料
        foreach ($del as $vo) {
            $disk = \Storage::disk('qiniu');
            $disk->delete($vo['path']);
        }
        //保存
        $imgUrls = \json_encode($imgUrls);

        //创建门派信息
        $sect = new Sect;
        $sect->city = $userInfo->city;
        $sect->name = $name;
        $sect->short_name = $shortName;
        $sect->head_avatar = $headAvatar;

        $sect->coach = $coach;
        $sect->tele = $tele;
        $sect->image = $imgUrls;
        $sect->charge = $charge;

        $sect->save();

        //写入成员信息
        $sectMember = new SectMember;
        $sectMember->sect_id = $sect->id;
        $sectMember->user_id = $userId;
        $sectMember->title = 10;
        $sectMember->save();

        return response()->json([
            'recode' => 1,
            'msg' => '创建成功',
            'sect' => [
                'sect_id' => $sect->id,
                'sect_title' => $sectMember->title,
                'sect_name' => $name,
                'sect_short_name' => $shortName,
            ],
        ]);

    }

    public function changeName(Request $request)
    {
        $sectId = request()->input('sect_id');
        $userId = request()->input('user_id');
        $name = request()->input('name');
        $shortName = request()->input('short_name');
        $file = $request->file("file");

        //检查是否能够修改
        $limitDay = Carbon::today()->subDays(180);
        $limit = SectChangeLog::where([['created_at', '>', $limitDay], ['sect_id', $sectId]])->first();
        if ($limit) {
            $nextDay = Carbon::parse($limit->created_at)->addDays(180)->toDateString();
            return response()->json([
                'recode' => 0,
                'msg' => '半年内只能修改一次,下次修改时间' . $nextDay,
            ]);
        }

        //检查队名是否存在
        $sectCheck = Sect::where([['id', '!=', $sectId], ['name', $name], ['status', '!=', 90]])->first();
        if ($sectCheck) {
            return response()->json([
                'recode' => 0,
                'msg' => '名称已经存在',
            ]);
        }

        $sect = Sect::find($sectId);

        if ($file) {
            $disk = \Storage::disk('qiniu');
            //删除旧图片
            $disk->delete($sect->head_avatar);
            $headAvatar = $disk->put('sect', $file);
            $sect->head_avatar = $headAvatar;
        }

        $sect->name = $name;
        $sect->short_name = $shortName;

        //写入变更记录
        $sectChangeLog = new SectChangeLog;
        $sectChangeLog->sect_id = $sectId;
        $sectChangeLog->user_id = $userId;

        \DB::transaction(function () use ($sect, $sectChangeLog) {
            $sect->save();
            $sectChangeLog->save();
        });

        return response()->json([
            'recode' => 1,
            'msg' => '更新成功',
        ]);

    }

    public function join()
    {
        $id = request()->input('id');
        $userId = request()->input('user_id');
        $sect = Sect::find($id);
        if ($sect == null || $sect->status == '90') {
            return response()->json([
                'recode' => 0,
                'msg' => '门派错误',
            ]);
        }
        $sectMember = SectMember::where('user_id', $userId)->first();
        if ($sectMember) {
            return response()->json([
                'recode' => 0,
                'msg' => '已经加入门派',
            ]);
        }
        //写入成员信息
        $sectMember = new SectMember;
        $sectMember->sect_id = $id;
        $sectMember->user_id = $userId;
        $sectMember->title = 90;
        $sectMember->save();

        //筹建门派检查人数
        if ($sect->status == 10) {
            $sectMemberCount = SectMember::where('sect_id', $id)->count();
            if ($sectMemberCount >= 3) {
                $sect->status = 20;
                $sect->save();
            }
        }

        return response()->json([
            'recode' => 1,
            'msg' => '加入成功',
            'sect' => [
                'sect_id' => $sect->id,
                'sect_title' => $sectMember->title,
                'sect_name' => $sect->name,
                'sect_short_name' => $sect->short_name,
            ],
        ]);

    }

    public function info()
    {
        $id = request()->input('id');
        $sect = Sect::find($id);
        if ($sect == null || $sect->status == '90') {
            return response()->json([
                'recode' => 0,
                'msg' => '门派错误',
            ]);
        }
        //将视频及图片转换为json
        $video = \json_decode($sect->video, true);
        $sect->video = $video ? $video : [];
        $image = \json_decode($sect->image, true);
        $sect->image = $image ? $image : [];

        //查询门派人数
        $memberCount = SectMember::where('sect_id', $id)->count();
        return response()->json([
            'recode' => 1,
            'info' => $sect,
            'member_count' => $memberCount,
        ]);

    }

    public function save()
    {
        $id = request()->input('id');
        $isReceive = request()->input('is_receive', 1);
        $scoreLimit = request()->input('score_limit', 0);
        $levelLimit = request()->input('level_limit', 0);
        $isOpen = request()->input('is_open', 0);
        $location = request()->input('location', '');
        $address = request()->input('address', '');
        $tableNum = request()->input('table_num', 0);
        $honor = request()->input('honor', '');
        $introduction = request()->input('introduction', '');
        $imgUrls = request()->input('imgurls', '');
        $videoUrls = request()->input('videourls', '');
        $tele = request()->input('tele', '');
        $opentime = request()->input('opentime', '');
        $del = request()->input('del');

        $arenaimgurls = request()->input('arenaimgurls', '');
        $arenadel = request()->input('arenadel');
        $coach = request()->input('coach');
        $charge = request()->input('charge');
        //删除旧资料
        foreach ($del as $vo) {
            $disk = \Storage::disk('qiniu');
            $disk->delete($vo['path']);
        }
        //保存
        $imgUrls = \json_encode($imgUrls);
        $arenaimgUrls = \json_encode($arenaimgurls);
        $videoUrls = \json_encode($videoUrls);

        $sect = Sect::find($id);
        if ($sect == null || $sect->status == '90') {
            return response()->json([
                'recode' => 0,
                'msg' => '门派错误',
            ]);
        }
        $sect->is_receive = $isReceive;
        $sect->score_limit = $scoreLimit;
        $sect->level_limit = $levelLimit;
        $sect->is_open = $isOpen;
        $sect->location = $location;
        $sect->address = $address;
        $sect->table_num = $tableNum;
        $sect->honor = $honor;
        $sect->introduction = $introduction;
        $sect->image = $imgUrls;
        $sect->video = $videoUrls;
        $sect->tele = $tele;
        $sect->opentime = $opentime;

        $sect->coach = $coach;
        $sect->arena_image = $arenaimgUrls;
        $sect->charge = $charge;

        $sect->save();
        return response()->json([
            'recode' => 1,
            'msg' => '保存成功',
        ]);
    }

    public function getBarcode()
    {
        $id = request()->input('id');
        $sect = Sect::find($id);
        if ($sect == null || $sect->status == '90') {
            return response()->json([
                'recode' => 0,
                'msg' => '门派错误',
            ]);
        }

        //产生身份二维码
        $barcodeName = 'sect_' . $id . '.png';
        $context = time() . '&2&' . $id;
        $context = base64_encode($context);
        $headAvatar = 'uploads/' . $sect->head_avatar;
        QrCode::encoding('UTF-8')->errorCorrection('H')->format('png')->size(200)->margin(0)->merge($headAvatar, .2, true)->generate($context, public_path('uploads/barcode/') . $barcodeName);
        //保存二维码地址
        $sect->id_barcode = $barcodeName;

        $sect->save();

        return response()->json([
            'recode' => 1,
            'sect' => $sect,
        ]);
    }

    public function getMyRanking()
    {
        $city = request()->input('city', '');
        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city .= '%';

        $sectId = request()->input('sect_id', 0);
        $sect = Sect::where([['status', 20], ['city', 'like', $city]])->find($sectId);
        $ranking = 0;
        if ($sect) {
            //查询门派地区排名
            $rank = Sect::where('city', 'like', $city);
            $rank = $rank->where('point', '>', $sect->point)->count();
            $ranking = $rank + 1;
            $ret = ['recode' => 1,
                'ranking' => $ranking,
                'info' => [
                    'head_img' => $sect->head_avatar,
                    'name' => $sect->name,
                    'point' => $sect->point,
                    'score' => $sect->score,
                ],
            ];
        } else {
            $ret = ['recode' => 1,
                'ranking' => $ranking,
            ];

        }

        return response()->json($ret);

    }

    public function getSectRanking()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $type = request()->input('type', 'point');
        $city = request()->input('city', '');
        $city = rtrim($city, '0');
        if (strlen($city) % 2 === 1) {
            $city = $city . '0';
        }
        $city .= '%';
        $keyword = request()->input('keyword', '');
        $keyword = '%' . $keyword . '%';

        $list = Sect::where([['city', 'like', $city], ['name', 'like', $keyword], ['status', 20]])
            ->select('id', 'name', 'head_avatar', 'point', 'score');
        $list = $list->orderBy('point', 'desc')
            ->paginate($pn);
        $ret = ['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()],
        ];
        return response()->json($ret);

    }

    public function getNearby()
    {
        $location = request()->input('location', '');
        $city = request()->input('city', '');
        if ($city == '' || $location == '') {
            return response()->json([
                'recode' => 0,
                'msg' => '请输入城市及地址',
            ]);
        }

        if(strpos($city,'11')===0 || strpos($city,'12')===0 || strpos($city,'31')===0 || strpos($city,'50')===0){
            //直辖市特殊处理
            $city = substr($city, 0, 3);
        }else{
            $city = substr($city, 0, 4);
        }
        $city .= '%';

        //获取球馆列表
        $latorlng = explode(",", $location);
        $sql="SELECT *,FLOOR(( 6371 * acos( cos( radians($latorlng[0]) ) * cos( radians(lat) ) * cos( radians(lng) - radians($latorlng[1]) ) + sin( radians($latorlng[0]) ) * sin( radians(lat) ) ) )*1000) AS distance
                    FROM (SELECT id,name, head_avatar, address, location,SUBSTRING_INDEX(location, ',', 1) AS lat,SUBSTRING_INDEX(SUBSTRING_INDEX(location, ',', -1), ',', 1) AS lng
                    FROM sects where is_open=1 and status=20) AS subquery HAVING distance IS NOT NULL ORDER BY distance asc";
        $list=DB::select($sql);
//        $list = Sect::where([ ['is_open', 1], ['status', 20]])->whereNotNull('location')
//            ->select('id', 'name', 'head_avatar', 'address', 'location')
//            ->get();
        //获取距离
        if (count($list) > 0) {
//            $to = "";
//            foreach ($list as $vo) {
//                $to .= ';' . $vo->location;
//            }
//            $to = substr($to, 1);
//            $QqMap = new QqMap();
//            $res = $QqMap->getDistance($location, $to);
//            if ($res['status'] != 0) {
//                return response()->json([
//                    'recode' => 0,
//                    'msg' => $res,
//                ]);
//            }
//
//            $disList = $res['result']['rows'][0]['elements'];
            return response()->json([
                'recode' => 1,
                'list' => $list,
//                'dislist' => $disList,
            ]);
        }

        return response()->json([
            'recode' => 0,
            'msg' => '附近没有球馆',
        ]);

    }
}
